package jane.mvc.sessions;

import jane.mvc.engine.JaneMVCContext;
import jane.mvc.utils.MyLog;
import jane.mvc.utils.Utils;

import java.util.Hashtable;
import java.util.UUID;

import javax.servlet.http.Cookie;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

public class MemorySession implements ISession
{

	UUID sessionID = null;

	JaneMVCContext ctx = null;

	// Hashtable<String, Object> sessionData = null;

	public MemorySession(JaneMVCContext context)
	{
		this.ctx = context;

		sessionID = new Utils().getNewUUID();
		Cookie cookie = new Cookie("janemvc", sessionID.toString());
		cookie.setMaxAge(-1);

		this.ctx.getResponse().addCookie(cookie);

		ActiveMemorySessions activesessions = ActiveMemorySessions
				.getInstance();

		Hashtable<String, Object> sessionData = new Hashtable<String, Object>();
		sessionData.put("__janemvc_created", DateTime.now(DateTimeZone.UTC));

		activesessions.put(sessionID.toString(), sessionData);

	}

	public UUID getID()
	{
		return sessionID;
	}

	public boolean put(String key, Object value)
	{
		try
		{
			ActiveMemorySessions activesessions = ActiveMemorySessions
					.getInstance();
			Hashtable<String, Object> sessionData = activesessions
					.get(sessionID.toString());

			sessionData.put(key, value);
			sessionData
					.put("__janemvc_updated", DateTime.now(DateTimeZone.UTC));

			activesessions.put(sessionID.toString(), sessionData);

		} catch (NullPointerException npex)
		{
			MyLog.severe("Inserting a null key or value into a session is not allowed.");
			return false;
		}

		return true;

	}

	public Object get(String key)
	{

		ActiveMemorySessions activesessions = ActiveMemorySessions
				.getInstance();
		Hashtable<String, Object> sessionData = activesessions.get(sessionID
				.toString());

		return sessionData.get(key);

	}

	public boolean delete(String key)
	{

		ActiveMemorySessions activesessions = ActiveMemorySessions
				.getInstance();
		Hashtable<String, Object> sessionData = activesessions.get(sessionID
				.toString());

		if (sessionData.remove(key) != null)
		{
			sessionData
					.put("__janemvc_updated", DateTime.now(DateTimeZone.UTC));

			activesessions.put(sessionID.toString(), sessionData);

			return true;
		} else
		{
			return false;
		}

	}

	public boolean save()
	{
		return true;
	}

	public boolean invalidate()
	{

		Cookie cookie = new Cookie("janemvc", sessionID.toString());
		cookie.setMaxAge(0);

		this.ctx.getResponse().addCookie(cookie);
		return false;
	}

}
